﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.SessionState;
using System.Data;
using System.IO;

using Newtonsoft.Json;
using Framework.DataAccess;
using Framework.Common.JsonEntities;
using Framework.Common;
using Framework.Common.Common;
using Mode;

namespace WebSite.WebServer
{
    /// <summary>
    /// EmpManage 的摘要说明
    /// </summary>
    public class EmpManage : IHttpHandler, IRequiresSessionState
    {
        JsonReturnMessages msg;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            msg = new JsonReturnMessages();
            try {
                string action = context.Request.Params["Action"];
                if (action == "AreaRolUserList")
                    AreaRolUserList();
                if (action == "AreRoleTree")
                    AreRoleTree();
                if (action == "AddItemUser")
                    AddItemUser();
                if (action == "StopItem")
                    StopItem();
                if (action == "UpdateItem")
                     UpdateItem();
                if (action == "GetTheDepartmentListJson2")
                    GetTheDepartmentListJson2();
                if (action == "UpUserRole")
                    UpUserRole();
                if (action == "GetAreRoleID")
                    GetAreRoleID();
                if (action == "IsSuperAdminstator")
                    IsSuperAdminstator();
            }
            catch (Exception err) {
                var message = err.Message;
                if (err.InnerException != null && err.InnerException.Message != null)
                    message += "<BR>" + err.InnerException.Message;

                msg.IsSuccess = 0;
                msg.Msg = message;

                var json = JsonConvert.SerializeObject(msg);
                context.Response.Write(json);
            }

            context.Response.End();
        }
        #region  改变该区域下的角色
        void UpUserRole()
        {
             var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();
            if (lu != null)
            {
               
                msg.IsSuccess = 0;
                if (lu.R_POWER == 1)
                {
                    int userid = context.Request.Params["id"].ToInt();
                    int aid = context.Request.Params["aid"].ToInt();
                    int jid = context.Request.Params["jid"].ToInt();
                    int rid = context.Request.Params["rid"].ToInt();

                    try
                    {
                        User u = new User();
                     
                        if (u.UpUserRole(userid,aid,jid,rid)> 0)
                        {
                            msg.IsSuccess = 1;
                            msg.Msg = "审核成功";
                        }
                        else
                        {
                            msg.Msg = "审核失败！";
                        }
                    }
                    catch (Exception er)
                    {
                        msg.Msg = er.Message;
                    }

                }
                else
                {
                    msg.Msg = "你没权限操作！";
                }
            }
            context.Response.Write(JsonConvert.SerializeObject(msg));
           
        }
        #endregion

        #region  屏蔽 启用
        void StopItem() { 
         var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();
            if (lu != null)
            {

                msg.IsSuccess = 0;
                if (lu.R_POWER == 1)
                {
                    int userid = context.Request.Params["userid"].ToInt();
                    int status = context.Request.Params["status"].ToInt();

                    try
                    {
                        User u = new User();
                        if (status == 0) status = 1;
                        else if (status == 1) status = 0;
                        if (u.UpdateUserStates(userid, status) > 0)
                        {
                            msg.IsSuccess = 1;
                            msg.Msg = "审核成功";
                        }
                        else
                        {
                            msg.Msg = "审核失败！";
                        }
                    }
                    catch (Exception er)
                    {
                        msg.Msg = er.Message;
                    }


                }
                else
                {
                    msg.Msg = "你没权限操作！";
                }
            }
            context.Response.Write(JsonConvert.SerializeObject(msg));
        }
        #endregion
        #region  添加一个用户
        void AddItemUser()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();
            if (lu != null)
            {

                  msg.IsSuccess = 0;
                  if (lu.R_POWER == 1)
                  {
                      RegInfo reg = new RegInfo();
                      reg.userid = context.Request.Params["userid"].ToInt();
                      reg.username = context.Request.Params["user"].ToStr();
                      reg.sex = context.Request.Params["sex"].ToStr();
                      reg.tel = context.Request.Params["tel"].ToStr();
                      reg.workcode = context.Request.Params["code"].ToStr();
                      reg.department = context.Request.Params["bm"].ToStr();
                      reg.email = context.Request.Params["email"].ToStr();
                      reg.areid = context.Request.Params["areroleid"].ToStr();
                      //string[] mm = context.Request.Params["areid"].Split(';');
                      //if (mm.Length > 0)
                      //    reg.areid = mm[mm.Length - 1];
                      //else
                      //    reg.areid = "0";
                      //reg.zw = context.Request.Params["zw"].ToStr();
                      //reg.zwid = context.Request.Params["zwid"].ToInt();
                      reg.pwd = context.Request.Params["pwd"].ToStr();
                      reg.status = 0;
                      try
                      {
                          User myuser = new User();
                          int R = myuser.OpUserItem(reg);
                          msg.IsSuccess = R;
                          msg.Msg = "";
                          if (R == 0)
                              msg.Msg = "添加失败";
                        
                      }
                      catch (Exception er) {
                          msg.Msg = er.Message;
                      }
                  }
                  else
                  {
                      msg.Msg = "你没权限操作！";
                  }
            
            }

            context.Response.Write(JsonConvert.SerializeObject(msg));
        }
        #endregion

        #region  修改
        void UpdateItem()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();
            if (lu != null)
            {

                msg.IsSuccess = 0;
                if (lu.R_POWER == 1)
                {
                    string pdata = context.Request.Params["data"];
                   

                    try
                    {
                        member_view mbItem = JsonConvert.DeserializeObject<member_view>(pdata);
                       


                        User myuser = new User();
                        int R = myuser.UpdateItem(mbItem);
                        msg.IsSuccess = R;
                        msg.Msg = "";
                        if (R == 0)
                            msg.Msg = "修改失败";

                    }
                    catch (Exception er)
                    {
                        msg.Msg = er.Message;
                    }
                }
                else
                {
                    msg.Msg = "你没权限操作！";
                }

            }

            context.Response.Write(JsonConvert.SerializeObject(msg));
        }
        #endregion

        #region  区域角色 下的 用户
        void AreaRolUserList()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();

            string Rjson = @"{""Rows"":null,""Total"":""0"",""Url"":""""}";
            if (lu != null)
            {
                string url = "";
                string fileName = context.Request.Params["fileName"].ToStr();

                url = "fileName=" + fileName;
                User u = new User();

                int areid = context.Request.Params["aid"].ToInt();
                int rolid = context.Request.Params["rid"].ToInt();
                int status = context.Request.Params["status"].ToInt(0);

                PageView pageInfo = new PageView();
                pageInfo.PageIndex = context.Request.Params["page"].ToInt(1);
                pageInfo.PageSize = context.Request.Params["pagesize"].ToInt(20);
                pageInfo.SortName = context.Request.Params["sortname"].ToStr();
                pageInfo.SortOrder = context.Request.Params["sortorder"].ToStr();
                pageInfo.SearchParams = context.Request.Params;

                url += "&aid=" + areid + "&rid=" + rolid;
                //url += "&userName=" + context.Request.Params["userName"].ToStr();


                PageList<object> List = u.GetTheRegUserList(areid, rolid, status, pageInfo);
              
                if (List.Data != null)
                {
                    Rjson = @"{""Rows"":" + List.Data.ToJson() + @",""Total"":""" + List.Total + @""",""Url"":""" + url + @"""}";
                }
              
            }
            context.Response.Write(Rjson);
        }
        #endregion

        #region  获得区域角色树
        void AreRoleTree()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }

            AreRoleTree art = new AreRoleTree(loginUser.A_ID);
            string v = art.ToJson(true);

            context.Response.Write(v);
        }
        #endregion
        #region    检测是否登陆


        /// <summary>
        /// 获得职务
        /// </summary>
        void GetTheDepartmentListJson2()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();
            List<JsonComboBox> items = new List<JsonComboBox>();
            if (lu != null)
            {
                int areid =  context.Request.Params["areaid"].ToInt();
                DataView dv = new User().GetTheDepartmentList(areid);
              
                if (dv != null)
                {
                    for (int i = 0; i < dv.Count; i++)
                    {
                        JsonComboBox dd = new JsonComboBox();
                        dd.id =  dv[i]["J_ID"].ToStr();
                        dd.text = dv[i]["R_NAME"].ToStr();

                        items.Add(dd);
                    }
                }
            }
            string reuslt = JsonConvert.SerializeObject(items);
            context.Response.Write(reuslt);
        }



        loginInfo chklogin()
        {
            try
            {
                return SessionShard.loginUser;
            }
            catch
            {
                msg.IsSuccess = -9;
                msg.Msg = "登陆失效，请重新登陆!";
                return null;
            }
        }
        #endregion

        // 获得区域-角色的关联ID
        void GetAreRoleID()
        {
            int result = -1;
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();
            List<JsonComboBox> items = new List<JsonComboBox>();
            if (lu != null)
            {
                int areid = context.Request.Params["aid"].ToInt(0);
                int roleid = context.Request.Params["rid"].ToInt(0);
                User u = new User();
                result = u.GetUserAreRoleID(areid, roleid);
            }
            context.Response.Write("{\"are_role_id\":\""+result+"\"}");
        }

        // 判断是否是洲级管理员
        void IsSuperAdminstator()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();
            List<JsonComboBox> items = new List<JsonComboBox>();
            if (lu != null)
            {
                User u = new User();
                int v = u.IsSuperAdministator(lu);
                context.Response.Write("{\"superadmin\":" + v + "}");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}